//
//  LPFRefreshControl.swift
//  WeiBo
//
//  Created by mac on 16/4/22.
//  Copyright © 2016年 mac. All rights reserved.
//

import UIKit

enum LPFRefreshControlType: Int{
    // 正常状态
    case Normal = 0
    // 松手刷新
    case Pulling = 1
    // 刷新中
    case Refreshing = 2
}
// 刷新控件的高度
private let RefreshHeight: CGFloat = 50

class LPFRefreshControl: UIControl {
    
    
    var lpfState: LPFRefreshControlType = .Normal{
        didSet{
            switch lpfState{
            case .Normal:
                messageLabel.text = "正常形态"
                // 我们上一个状态为Refreshing 在执行动画
                if oldValue == .Refreshing{
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        self.scrollView?.contentInset.top -= RefreshHeight
                    })
                }
            case .Pulling:
                messageLabel.text = "松手刷新"
            case .Refreshing:
                messageLabel.text = "刷新中"
                //设置动画
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    self.scrollView?.contentInset.top += 50
                    }, completion: { (_) -> Void in
                        //告知外界要刷新了
                        self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
                })
            }
        }
    }
    
    
    // scrollView
    var scrollView: UIScrollView?
    
    // MARK: - 供外界调用停止刷新
    func endRefreshing(){
        lpfState = .Normal
    }

    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    // MARK: - 设置视图
    private func setupUI(){
        self.backgroundColor = RGB(red: 55, green: 105, blue: 65)
        
        addSubview(messageLabel)
    }
    
    // MARK: - 懒加载控件
    private lazy var messageLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(14)
        label.text = "正常状态"
        label.textAlignment = .Center
        label.textColor = UIColor.whiteColor()
        return label
    }()
    
    // MARK: - 设置frame KVO 监听变化
    override func layoutSubviews() {
        super.layoutSubviews()
        
        // 设置当前控件的frame
        self.frame = CGRect(x: 0, y: -RefreshHeight, width: SCREENW, height: RefreshHeight)
        
        messageLabel.frame = CGRect(x: 0, y: 0, width: SCREENW, height: RefreshHeight)
    }
    // 通过该方法监听 添加到谁身上了
    override func willMoveToSuperview(newSuperview: UIView?) {
        // 判断父控件是否存在 且是否是 UIScrollView
        if let scrollView = newSuperview as? UIScrollView{
            // 通过kvo 监听我们父控件的属性改变
            self.scrollView = scrollView
            scrollView.addObserver(self, forKeyPath: "contentOffset", options: NSKeyValueObservingOptions.New, context: nil)
        }
    }
    
    // 监听我们那个对象的属性发生改变 
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        // 获得scrollView?.contentOffset.y
        let contentOffsetY = scrollView?.contentOffset.y
        
        // 通过dragging 来判断我们是否在拖动scrollView
        if scrollView!.dragging{
            // 代表拖动中
            if contentOffsetY > -144 && lpfState == .Pulling{
                lpfState = .Normal
            }else if contentOffsetY <= -144 && lpfState == .Normal{
                lpfState = .Pulling
            }
        }else{
            // 代表停止拖动
            if lpfState == .Pulling{
                lpfState = .Refreshing
            }
        }
    }
    
    // KVO 需要程序员自己手动移除
    deinit{
        self.scrollView?.removeObserver(self, forKeyPath: "contentOffset")
    }
}
